package com.yyz.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.yyz.common.BaseContext;
import com.yyz.domain.AddressBook;
import com.yyz.mapper.AddressBookMapper;
import com.yyz.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yyz
 * @create 2023-07-25 13:51
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void insert(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getThreadLocal());
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询全部地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getThreadLocal());

        List<AddressBook> addressBooks = addressBookMapper.selectList(lqw);
        return addressBooks;
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(AddressBook::getIsDefault,1)
                .eq(AddressBook::getUserId,BaseContext.getThreadLocal());
        lqw.set(AddressBook::getIsDefault,0);

        addressBookMapper.update(addressBook,lqw);

        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook selectById(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    /**
     * 获取默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getIsDefault,1).eq(AddressBook::getUserId,BaseContext.getThreadLocal());

        AddressBook addressBook = addressBookMapper.selectOne(lqw);
        return addressBook;
    }
}
